#include "databaseconnection.h"
#include <QSqlDatabase>
#include <QCryptographicHash>
#include <QFile>
#include <QSqlQuery>
#include <QStringList>
#include <QVariant>

DatabaseConnection::DatabaseConnection(QObject *parent) :
        QObject(parent)
{
    databaseFile="";
}

DatabaseConnection::DatabaseConnection(QString dbFile, QObject *parent) :
        QObject(parent)
{
    databaseFile = dbFile;
}

/**
* @brief get the database
*
* @return the database object
*
*  Makes sure the database identified by dbname exists and is open()
*  If it is not yet loaded/does not exist it is created and populated
*  with default data.
*/
QSqlDatabase DatabaseConnection::getDatabase()
{
    /* if it is already open, just return it */
    QSqlDatabase db = QSqlDatabase::database("core");
    if(db.isValid())
    {
        Q_ASSERT(db.open());
        return db;
    }

    db = QSqlDatabase::addDatabase("QSQLITE","core");

    if (QFile::exists(databaseFile))
    {
        // if the file existed on filesystem, we assume it already has correct format
        // FIXME: check database version
        db.setDatabaseName(databaseFile);
        Q_ASSERT(db.open());
    }
    else
    {
        // the file does not exist on filesystem, so populate it with data

        db.setDatabaseName(databaseFile);
        Q_ASSERT(db.open());
        QSqlQuery q(db);
        QStringList sl;
        sl.append("CREATE TABLE users (id INTEGER PRIMARY KEY, lastactive TEXT, level NUMERIC, name TEXT, password TEXT)");
        foreach (QString f, sl)
        {
            q.exec(f);
        }
    }
    return db;
}

bool DatabaseConnection::authUser(QString username,QString password)
{
    // MD5 Hash-function
    QCryptographicHash *pHash = new QCryptographicHash(QCryptographicHash::Md5);
    // hash the password with MD5
    pHash->addData(password.toUtf8());

    QSqlQuery *q = getQuery();

    q->prepare("SELECT name FROM users WHERE name = :name AND password = :password");
    q->bindValue(":name",QVariant(username));
    q->bindValue(":password",QString(pHash->result().toHex()));
    q->exec();
    if(!q->first())
    {
        return false;
    }
    return true;
}

QSqlQuery* DatabaseConnection::getQuery()
{
    return new QSqlQuery(getDatabase());
}

/**
QList<QXmppRoster::QXmppRosterEntry> DatabaseConnection::getRosterEntries(QString username, QString accountJid) {
    QSqlQuery* q = getQuery();
    q->prepare("SELECT groups.name as grp,buddies.alias as alias, buddies.subscription_status as subscription_status,"
               "buddies.subscription_type as subscription_type,buddies.jid as jid  FROM buddies JOIN groups "
               " ON buddies.jid = groups.jid WHERE buddies.username = :uname AND groups.username = :uname"
               " AND buddies.accountjid = :accjid");
    // 0 group name
    // 1 buddy alias
    // 2 subscription status
    // 3 subscription type
    // 4 jid
    q->bindValue(":uname",QVariant(username));
    q->bindValue(":acchid",QVariant(accountJid));
    q->exec();
    QList<QXmppRoster::QXmppRosterEntry> buddies;
    QSet<QString> groups;
    QXmppRoster::QXmppRosterEntry buddy;
    while (q->next()) {
        if(q->value(4) == buddy.bareJid())
        {
            // appending group
            groups.insert(q->value(0).toString());
            continue;
        }
        else {
            if(q->value(4) != "")
            {
                buddy.setGroups(groups);
                buddies.append(buddy);
            }
            buddy.setBareJid(q->value(4).toString());
            buddy.setName(q->value(1).toString());
            buddy.setSubscriptionStatus(q->value(2).toString());
            //buddy.setSubscriptionTypeFromStr(q->value(3).toString());
        }
    }
    return buddies;
}
*/
